package org.jackysoft.opensymphony.workflow.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.opensymphony.workflow.InvalidOwnerException;
import org.jackysoft.opensymphony.workflow.WorkflowException;
import org.jackysoft.opensymphony.workflow.entity.ResultDescriptor;
import org.jackysoft.service.VariableSettingService;
import org.jackysoft.service.VariableService;
import org.jackysoft.util.StringUtils;
import org.jackysoft.workflow.StepOwner;


public class OwnerResolver {
	private static final Log logger = LogFactory.getLog(OwnerResolver.class);
	private VariableResolver variableResolver;
	private Map transientVars;
	private VariableService ws;
	private Map<Integer, String> ownerMap;
	private VariableSettingService varSetting;

	public OwnerResolver(Collection<StepOwner> owners,
			VariableResolver variableResolver, Map transientVars,
			VariableService ws, VariableSettingService ps) {
		varSetting = ps;
		this.variableResolver = variableResolver;
		this.transientVars = transientVars;
		this.ws = ws;
		ownerMap = new HashMap<Integer, String>(owners.size());
		for (StepOwner so : owners) {
			Integer stepId = Integer.parseInt(so.getStepId());
			if (so.getOwner().startsWith("${")) {
				Object ow = this.variableResolver.translateVariables(so.getOwner(), transientVars, ws, varSetting);
				ownerMap.put(stepId,(String) ow);

			} else {
				ownerMap.put(stepId, so.getOwner());
			}

		}

	}

	public void setOwner(ResultDescriptor rd, WorkflowResultType wt)
			throws WorkflowException {
	
		String sowner = null;//rd.getOwner();
		// 从变量中萃取
		boolean vempty = false;
		if (StringUtils.isBlank(sowner)) {
			vempty = true;
			Object o = variableResolver.translateVariables(sowner,
					transientVars, ws, varSetting);
			sowner = (o != null) ? o.toString() : null;
		}
		logger.info("已经配置的用户 "+sowner);
		switch (wt) {
		case 正常分支: {
			Integer stepId = rd.getStep();
			// 动态设置owner
			if (vempty)
				sowner = ownerMap.get(stepId);
			logger.info("工作转向:" + sowner);
		}
			;
			break;
		case 会签分支: {

		}
			;
			break;
		case 正常汇聚:
		case 普通单步: {
			if (vempty)
				sowner = ownerMap.values().iterator().next();
			logger.info("工作转向:" + sowner);
		}
			;
			break;
		default:
			throw new IllegalStateException("未知状态 " + wt);
		}
		vempty = StringUtils.isEmpty(sowner);
		if (vempty)
			throw new InvalidOwnerException("用户变量没有设置...");
		    logger.info("设置办理人: " + sowner);
		rd.setOwner(sowner);

	}

	public Map<Integer, String> getOwnerMap() {
		return ownerMap;
	}

}
